package org.osprey.apidoc.verticle;

import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.json.Json;
import io.vertx.ext.web.RoutingContext;
import org.osprey.apidoc.common.ApiHandler;
import org.osprey.apidoc.common.RestfulApiVerticle;
import org.osprey.apidoc.common.RouterVerticle;
import org.osprey.apidoc.pojo.User;
import org.osprey.apidoc.service.UserService;
import org.osprey.apidoc.service.impl.UserServiceImpl;

import java.util.Arrays;

/**
 * @ClassName UserVerticle
 * @Description: 用户相关
 * @Author Osprey
 * @Date 2019/10/16
 * @Version V2.0
 **/
public class UserVerticle extends RestfulApiVerticle implements RouterVerticle {

    private UserService userService;


    @Override
    public void start() throws Exception {
        super.start();
        this.userService = new UserServiceImpl(vertx, config());
        routers.addAll(Arrays.asList(new ApiHandler(HttpMethod.POST, "/login", this::userLogin)));
    }

    /**
     * 用户登录
     * @param context
     */
    private void userLogin(RoutingContext context) {
        String userName = context.request().getParam("userName");
        String password = context.request().getParam("password");

        userService.login(userName, password, resultHandlerNonEmpty(context));

    }

    /**
     * This method generates handler for async methods in REST APIs.
     * The result requires non-empty. If empty, return <em>404 Not Found</em> status.
     * The content type is JSON.
     *
     * @param context routing context instance
     * @param <T>     result type
     * @return generated handler
     */
    protected <T> Handler<AsyncResult<T>> resultHandlerNonEmpty(RoutingContext context) {
        return ar -> {
            if (ar.succeeded()) {
                T res = ar.result();
                if (res == null) {
                    notFound(context);
                } else {
                    context.response()
                            .putHeader("content-type", "application/json")
                            .end(res.toString());
                }
            } else {
                internalError(context, ar.cause());
                ar.cause().printStackTrace();
            }
        };
    }

}
